#include "device_state_manager.h"
#include "led_control_center.h"

// ==================== 构造和析构方法 ====================

DeviceStateManager::DeviceStateManager() {
  // 初始化核心状态
  systemState = STATE_IDLE;
  deviceState = DEVICE_ACTIVE;
  networkState = NETWORK_DISCONNECTED;
  
  // 初始化状态缓存
  cachedSystemState = STATE_IDLE;
  lastCacheUpdate = 0;
  
  // 初始化历史记录
  historyIndex = 0;
  historyCount = 0;
  memset(stateHistory, 0, sizeof(stateHistory));
  
  // 初始化外部依赖
  ledControlCenter = nullptr;
  
  // 初始化线程安全对象
  stateMutex = NULL;
  historyMutex = NULL;
  
  // 初始化回调函数
  stateChangeCallback = NULL;
  networkStateCallback = NULL;
  drawingProgressCallback = NULL;
  
  // 初始化绘图会话（使用结构体的reset方法）
  drawingSession.reset();
}

DeviceStateManager::~DeviceStateManager() {
  // 清理线程安全对象
  if (stateMutex != NULL) {
    vSemaphoreDelete(stateMutex);
    stateMutex = NULL;
  }
  
  if (historyMutex != NULL) {
    vSemaphoreDelete(historyMutex);
    historyMutex = NULL;
  }
  
  // 清理外部依赖引用
  ledControlCenter = nullptr;
  
  // 清理回调函数
  stateChangeCallback = NULL;
  networkStateCallback = NULL;
  drawingProgressCallback = NULL;
}

// ==================== 初始化方法 ====================

bool DeviceStateManager::begin(LEDControlCenter* ledControl) {
  Serial.println("🔧 初始化设备状态管理器...");
  
  // 设置外部依赖
  ledControlCenter = ledControl;
  
  // 创建状态保护互斥锁
  stateMutex = xSemaphoreCreateMutex();
  if (stateMutex == NULL) {
    Serial.println("❌ 设备状态管理器初始化失败：无法创建状态互斥锁");
    return false;
  }
  
  // 创建历史记录保护互斥锁
  historyMutex = xSemaphoreCreateMutex();
  if (historyMutex == NULL) {
    Serial.println("❌ 设备状态管理器初始化失败：无法创建历史互斥锁");
    vSemaphoreDelete(stateMutex);
    stateMutex = NULL; 
    return false;
  }
  
  // 初始化状态缓存
  updateStateCache();
  
  // 记录初始状态到历史
  addStateToHistory(STATE_IDLE, STATE_IDLE, "系统初始化");
  
  Serial.println("✅ 设备状态管理器初始化成功");
  Serial.printf("   - 状态互斥锁: 已创建\n");
  Serial.printf("   - 历史互斥锁: 已创建\n");
  Serial.printf("   - LED控制中心: %s\n", ledControl ? "已连接" : "未连接");
  Serial.printf("   - 初始状态: %s\n", stateToString(systemState).c_str());
  
  return true;
}

void DeviceStateManager::reset() {
  Serial.println("🔄 重置设备状态管理器...");
  
  if (takeMutexWithRetry(stateMutex)) {
    // 重置核心状态
    systemState = STATE_IDLE;
    deviceState = DEVICE_ACTIVE;
    networkState = NETWORK_DISCONNECTED;
    
    // 重置绘图会话
    drawingSession.reset();
    
    xSemaphoreGive(stateMutex);
  }
  
  // 清理状态历史
  clearStateHistory();
  
  // 更新缓存
  updateStateCache();
  
  Serial.println("✅ 设备状态管理器重置完成");
}

// ==================== 内部辅助方法 ====================

bool DeviceStateManager::takeMutexWithRetry(SemaphoreHandle_t mutex, TickType_t timeout) {
  if (mutex == NULL) {
    return false;
  }
  
  // 尝试获取互斥锁，带重试机制
  for (uint32_t retry = 0; retry < DeviceStateConfig::MUTEX_TAKE_RETRY; retry++) {
    if (xSemaphoreTake(mutex, timeout) == pdTRUE) {
      return true;
    }
    
    // 短暂延迟后重试
    vTaskDelay(pdMS_TO_TICKS(10));
  }
  
  Serial.printf("⚠️ 互斥锁获取失败，重试%d次后放弃\n", DeviceStateConfig::MUTEX_TAKE_RETRY);
  return false;
}

void DeviceStateManager::addStateToHistory(SystemState fromState, SystemState toState, const String& reason) {
  if (takeMutexWithRetry(historyMutex)) {
    // 添加新的状态转换记录
    StateTransition& transition = stateHistory[historyIndex];
    transition.fromState = fromState;
    transition.toState = toState;
    transition.timestamp = millis();
    transition.reason = reason;
    
    // 更新索引（循环缓冲区）
    historyIndex = (historyIndex + 1) % DeviceStateConfig::MAX_STATE_HISTORY;
    
    // 更新记录数量
    if (historyCount < DeviceStateConfig::MAX_STATE_HISTORY) {
      historyCount++;
    }
    
    xSemaphoreGive(historyMutex);
  }
}

bool DeviceStateManager::isValidStateTransition(SystemState fromState, SystemState toState) {
  // 定义有效的状态转换矩阵
  static const bool validTransitions[STATE_MAX][STATE_MAX] = {
    // 从 STATE_IDLE 可以转换到
    {true,  true,  true,   true,  true},  // IDLE -> IDLE/HOMING/DRAWING/EMERGENCY/MAINTENANCE
    // 从 STATE_HOMING 可以转换到  
    {true,  true,  true,   true,  true},  // HOMING -> IDLE/HOMING/DRAWING/EMERGENCY/MAINTENANCE
    // 从 STATE_DRAWING 可以转换到
    {true,  true,  true,   true,  true},  // DRAWING -> IDLE/HOMING/DRAWING/EMERGENCY/MAINTENANCE
    // 从 STATE_EMERGENCY 可以转换到
    {true,  false, false,  true,  true},  // EMERGENCY -> IDLE/EMERGENCY/MAINTENANCE
    // 从 STATE_MAINTENANCE 可以转换到
    {true,  true,  true,   true,  true},  // MAINTENANCE -> IDLE/HOMING/DRAWING/EMERGENCY/MAINTENANCE
  };
  
  if (fromState >= STATE_MAX || toState >= STATE_MAX) {
    return false;
  }
  
  return validTransitions[fromState][toState];
}

void DeviceStateManager::updateStateCache() {
  cachedSystemState = systemState;
  lastCacheUpdate = millis();
}

String DeviceStateManager::stateToString(SystemState state) {
  switch (state) {
    case STATE_IDLE: return "IDLE";
    case STATE_HOMING: return "HOMING";
    case STATE_DRAWING: return "DRAWING";
    case STATE_EMERGENCY: return "EMERGENCY";
    case STATE_MAINTENANCE: return "MAINTENANCE";
    default: return "UNKNOWN";
  }
}

String DeviceStateManager::deviceStateToString(DeviceRunState state) {
  switch (state) {
    case DEVICE_SLEEPING: return "SLEEPING";
    case DEVICE_ACTIVE: return "ACTIVE";
    case DEVICE_STANDBY: return "STANDBY";
    default: return "UNKNOWN";
  }
}

String DeviceStateManager::networkStateToString(NetworkState state) {
  switch (state) {
    case NETWORK_DISCONNECTED: return "DISCONNECTED";
    case NETWORK_CONNECTING: return "CONNECTING";
    case NETWORK_CONNECTED: return "CONNECTED";
    case NETWORK_MQTT_CONNECTED: return "MQTT_CONNECTED";
    case NETWORK_ERROR: return "ERROR";
    default: return "UNKNOWN";
  }
}

// ==================== 系统状态管理方法 ====================

bool DeviceStateManager::setSystemState(SystemState newState, const String& reason) {
  // 输入验证
  if (newState >= STATE_MAX) {
    Serial.printf("❌ 无效的系统状态: %d\n", newState);
    return false;
  }
  
  if (!takeMutexWithRetry(stateMutex)) {
    Serial.println("❌ 无法获取状态互斥锁，设置系统状态失败");
    return false;
  }
  
  SystemState oldState = systemState;
  
  // 检查状态转换是否有效
  if (!isValidStateTransition(oldState, newState)) {
    xSemaphoreGive(stateMutex);
    Serial.printf("❌ 无效的状态转换: %s -> %s\n", 
                  stateToString(oldState).c_str(), 
                  stateToString(newState).c_str());
    return false;
  }
  
  // 状态相同时直接返回成功
  if (oldState == newState) {
    xSemaphoreGive(stateMutex);
    return true;
  }
  
  // 更新状态
  systemState = newState;
  
  // 更新缓存
  updateStateCache();
  
  xSemaphoreGive(stateMutex);
  
  // 在释放锁后进行耗时操作
  
  // 添加到状态历史
  String fullReason = reason.isEmpty() ? "状态转换" : reason;
  addStateToHistory(oldState, newState, fullReason);
  
  // 调用状态变化回调
  if (stateChangeCallback != NULL) {
    stateChangeCallback(oldState, newState);
  }
  
  // LED控制中心处理
  if (ledControlCenter != nullptr) {
    switch (newState) {
      case STATE_IDLE:
        if (oldState == STATE_DRAWING) {
          ledControlCenter->endDrawingSession();
        } else {
          ledControlCenter->requestStatusChange(LED_IDLE, "系统进入空闲状态");
        }
        break;
      case STATE_HOMING:
        ledControlCenter->requestStatusChange(LED_HOMING, "系统开始归零");
        break;
      case STATE_DRAWING:
        ledControlCenter->requestStatusChange(LED_DRAWING, "系统进入绘图状态");
        break;
      case STATE_EMERGENCY:
        ledControlCenter->requestStatusChange(LED_EMERGENCY, "系统紧急停止");
        break;
      case STATE_MAINTENANCE:
        ledControlCenter->requestStatusChange(LED_MAINTENANCE, "系统进入维护模式");
        break;
      default:
        break;
    }
  }
  
  // 记录状态变化日志
  Serial.printf("🎯 系统状态变化: %s -> %s (%s)\n", 
                stateToString(oldState).c_str(), 
                stateToString(newState).c_str(),
                fullReason.c_str());
  
  return true;
}

SystemState DeviceStateManager::getSystemState(bool useCache) {
  // 如果启用缓存且缓存有效，直接返回缓存值
  if (useCache && (millis() - lastCacheUpdate) < DeviceStateConfig::STATE_CACHE_VALID_MS) {
    return cachedSystemState;
  }
  
  SystemState state = STATE_IDLE;
  if (takeMutexWithRetry(stateMutex)) {
    state = systemState;
    
    // 更新缓存
    if (useCache) {
      cachedSystemState = state;
      lastCacheUpdate = millis();
    }
    
    xSemaphoreGive(stateMutex);
  }
  return state;
}

String DeviceStateManager::getSystemStateString(bool useCache) {
  SystemState state = getSystemState(useCache);
  return stateToString(state);
}

// ==================== 设备运行状态管理方法 ====================

bool DeviceStateManager::setDeviceState(DeviceRunState newState, const String& reason) {
  // 输入验证
  if (newState >= DEVICE_MAX) {
    Serial.printf("❌ 无效的设备状态: %d\n", newState);
    return false;
  }
  
  if (!takeMutexWithRetry(stateMutex)) {
    Serial.println("❌ 无法获取状态互斥锁，设置设备状态失败");
    return false;
  }
  
  DeviceRunState oldState = deviceState;
  
  // 状态相同时直接返回成功
  if (oldState == newState) {
    xSemaphoreGive(stateMutex);
    return true;
  }
  
  // 更新状态
  deviceState = newState;
  
  xSemaphoreGive(stateMutex);
  
  // 记录状态变化日志
  String fullReason = reason.isEmpty() ? "设备状态转换" : reason;
  Serial.printf("🔋 设备状态变化: %s -> %s (%s)\n", 
                deviceStateToString(oldState).c_str(),
                deviceStateToString(newState).c_str(),
                fullReason.c_str());
  
  return true;
}

DeviceRunState DeviceStateManager::getDeviceState() {
  DeviceRunState state = DEVICE_ACTIVE;
  if (takeMutexWithRetry(stateMutex)) {
    state = deviceState;
    xSemaphoreGive(stateMutex);
  }
  return state;
}

String DeviceStateManager::getDeviceStateString() {
  DeviceRunState state = getDeviceState();
  return deviceStateToString(state);
}

bool DeviceStateManager::isDeviceActive() {
  return getDeviceState() == DEVICE_ACTIVE;
}

bool DeviceStateManager::isDeviceSleeping() {
  return getDeviceState() == DEVICE_SLEEPING;
}

// ==================== 网络状态管理方法 ====================

bool DeviceStateManager::setNetworkState(NetworkState newState, const String& reason) {
  // 输入验证
  if (newState >= NETWORK_MAX) {
    Serial.printf("❌ 无效的网络状态: %d\n", newState);
    return false;
  }
  
  if (!takeMutexWithRetry(stateMutex)) {
    Serial.println("❌ 无法获取状态互斥锁，设置网络状态失败");
    return false;
  }
  
  NetworkState oldState = networkState;
  
  // 状态相同时直接返回成功
  if (oldState == newState) {
    xSemaphoreGive(stateMutex);
    return true;
  }
  
  // 更新状态
  networkState = newState;
  
  xSemaphoreGive(stateMutex);
  
  // 调用网络状态变化回调
  if (networkStateCallback != NULL) {
    networkStateCallback(oldState, newState);
  }
  
  // 记录状态变化日志
  String fullReason = reason.isEmpty() ? "网络状态转换" : reason;
  Serial.printf("🌐 网络状态变化: %s -> %s (%s)\n", 
                networkStateToString(oldState).c_str(),
                networkStateToString(newState).c_str(),
                fullReason.c_str());
  
  return true;
}

NetworkState DeviceStateManager::getNetworkState() {
  NetworkState state = NETWORK_DISCONNECTED;
  if (takeMutexWithRetry(stateMutex)) {
    state = networkState;
    xSemaphoreGive(stateMutex);
  }
  return state;
}

String DeviceStateManager::getNetworkStateString() {
  NetworkState state = getNetworkState();
  return networkStateToString(state);
}

bool DeviceStateManager::isNetworkConnected() {
  NetworkState state = getNetworkState();
  return (state == NETWORK_CONNECTED || state == NETWORK_MQTT_CONNECTED);
}

bool DeviceStateManager::isMQTTConnected() {
  return getNetworkState() == NETWORK_MQTT_CONNECTED;
}

// ==================== 绘图会话管理方法 ====================

bool DeviceStateManager::startDrawingSession(const String& patternName, uint32_t totalPoints, bool isStreamMode) {
  // 输入验证
  if (patternName.isEmpty() || totalPoints == 0) {
    Serial.println("❌ 绘图会话参数无效");
    return false;
  }
  
  if (!takeMutexWithRetry(stateMutex)) {
    Serial.println("❌ 无法获取状态互斥锁，开始绘图会话失败");
    return false;
  }
  
  // 检查是否已有活跃会话
  if (drawingSession.isActive) {
    xSemaphoreGive(stateMutex);
    Serial.println("❌ 已有活跃的绘图会话，无法开始新会话");
    return false;
  }
  
  // 初始化绘图会话
  drawingSession.isActive = true;
  drawingSession.isPaused = false;
  drawingSession.isStreamMode = isStreamMode;
  drawingSession.currentIndex = 0;
  drawingSession.totalPoints = totalPoints;
  drawingSession.setPatternName(patternName);
  drawingSession.startTime = millis();
  drawingSession.lastUpdateTime = millis();
  drawingSession.progressPercent = 0.0f;
  drawingSession.estimatedTimeLeft = 0;
  
  xSemaphoreGive(stateMutex);
  
  Serial.printf("🎨 开始绘图会话: %s (%d点, %s模式)\n", 
                patternName.c_str(), totalPoints, 
                isStreamMode ? "流式" : "传统");
  
  return true;
}

bool DeviceStateManager::pauseDrawingSession(uint32_t currentIndex) {
  if (!takeMutexWithRetry(stateMutex)) {
    Serial.println("❌ 无法获取状态互斥锁，暂停绘图会话失败");
    return false;
  }
  
  if (!drawingSession.isActive) {
    xSemaphoreGive(stateMutex);
    Serial.println("❌ 没有活跃的绘图会话可暂停");
    return false;
  }
  
  if (drawingSession.isPaused) {
    xSemaphoreGive(stateMutex);
    Serial.println("⚠️ 绘图会话已处于暂停状态");
    return true;
  }
  
  drawingSession.isPaused = true;
  drawingSession.currentIndex = currentIndex;
  drawingSession.lastUpdateTime = millis();
  
  xSemaphoreGive(stateMutex);
  
  Serial.printf("⏸️ 绘图会话暂停: 索引=%d\n", currentIndex);
  return true;
}

bool DeviceStateManager::resumeDrawingSession() {
  if (!takeMutexWithRetry(stateMutex)) {
    Serial.println("❌ 无法获取状态互斥锁，恢复绘图会话失败");
    return false;
  }
  
  if (!drawingSession.isActive) {
    xSemaphoreGive(stateMutex);
    Serial.println("❌ 没有活跃的绘图会话可恢复");
    return false;
  }
  
  if (!drawingSession.isPaused) {
    xSemaphoreGive(stateMutex);
    Serial.println("⚠️ 绘图会话未处于暂停状态");
    return true;
  }
  
  drawingSession.isPaused = false;
  drawingSession.lastUpdateTime = millis();
  
  xSemaphoreGive(stateMutex);
  
  Serial.println("▶️ 绘图会话恢复");
  return true;
}

bool DeviceStateManager::endDrawingSession() {
  if (!takeMutexWithRetry(stateMutex)) {
    Serial.println("❌ 无法获取状态互斥锁，结束绘图会话失败");
    return false;
  }
  
  if (!drawingSession.isActive) {
    xSemaphoreGive(stateMutex);
    Serial.println("⚠️ 没有活跃的绘图会话可结束");
    return true;
  }
  
  // 记录会话信息用于日志
  unsigned long duration = millis() - drawingSession.startTime;
  String patternName = drawingSession.getPatternName();
  uint32_t completedPoints = drawingSession.currentIndex;
  uint32_t totalPoints = drawingSession.totalPoints;
  
  // 重置绘图会话
  drawingSession.reset();
  
  xSemaphoreGive(stateMutex);
  
  // 计算完成率
  float completionRate = totalPoints > 0 ? (float)completedPoints / totalPoints * 100.0f : 0.0f;
  
  Serial.printf("🎉 绘图会话结束: %s (完成%d/%d点, %.1f%%, 耗时%.1fs)\n", 
                patternName.c_str(), completedPoints, totalPoints, 
                completionRate, duration / 1000.0);
  
  return true;
}

bool DeviceStateManager::updateDrawingProgress(uint32_t currentIndex) {
  if (!takeMutexWithRetry(stateMutex)) {
    return false;
  }
  
  if (!drawingSession.isActive) {
    xSemaphoreGive(stateMutex);
    return false;
  }
  
  // 检查更新间隔，避免过于频繁的更新
  unsigned long currentTime = millis();
  if (currentTime - drawingSession.lastUpdateTime < DeviceStateConfig::DRAWING_PROGRESS_UPDATE_INTERVAL) {
    xSemaphoreGive(stateMutex);
    return true;
  }
  
  drawingSession.currentIndex = currentIndex;
  drawingSession.lastUpdateTime = currentTime;
  
  // 计算进度百分比
  if (drawingSession.totalPoints > 0) {
    drawingSession.progressPercent = (float)currentIndex / drawingSession.totalPoints * 100.0f;
    
    // 估算剩余时间
    if (currentIndex > 0) {
      unsigned long elapsed = currentTime - drawingSession.startTime;
      float avgTimePerPoint = (float)elapsed / currentIndex;
      uint32_t remainingPoints = drawingSession.totalPoints - currentIndex;
      drawingSession.estimatedTimeLeft = (uint32_t)(avgTimePerPoint * remainingPoints / 1000);
    }
  }
  
  xSemaphoreGive(stateMutex);
  
  // 调用进度回调
  if (drawingProgressCallback != NULL) {
    drawingProgressCallback(currentIndex, drawingSession.totalPoints);
  }
  
  return true;
}

DrawingSession DeviceStateManager::getDrawingSession() {
  DrawingSession session;
  if (takeMutexWithRetry(stateMutex)) {
    session = drawingSession;
    xSemaphoreGive(stateMutex);
  }
  return session;
}

bool DeviceStateManager::isDrawingActive() {
  DrawingSession session = getDrawingSession();
  return session.isActive && !session.isPaused;
}

bool DeviceStateManager::isDrawingPaused() {
  DrawingSession session = getDrawingSession();
  return session.isActive && session.isPaused;
}

float DeviceStateManager::getDrawingProgress() {
  DrawingSession session = getDrawingSession();
  return session.progressPercent;
}

uint32_t DeviceStateManager::getEstimatedTimeLeft() {
  DrawingSession session = getDrawingSession();
  return session.estimatedTimeLeft;
}

// ==================== 状态查询和报告方法 ====================

String DeviceStateManager::getStatusReport() {
  String report = "=== 设备状态报告 ===\n";
  
  report += "系统状态: " + getSystemStateString() + "\n";
  report += "设备状态: " + getDeviceStateString() + "\n";
  report += "网络状态: " + getNetworkStateString() + "\n";
  
  DrawingSession session = getDrawingSession();
  if (session.isActive) {
    report += "绘图状态: ";
    report += (session.isPaused ? "暂停" : "进行中");
    report += "\n";
    report += "当前图案: " + session.getPatternName() + "\n";
    if (session.totalPoints > 0) {
      report += "绘图进度: ";
      report += String(session.currentIndex) + "/" + String(session.totalPoints);
      report += " (" + String(session.progressPercent, 1) + "%)\n";
      if (session.estimatedTimeLeft > 0) {
        report += "预计剩余时间: " + String(session.estimatedTimeLeft) + "秒\n";
      }
    }
  } else {
    report += "绘图状态: 空闲\n";
  }
  
  return report;
}

String DeviceStateManager::getDetailedStatus() {
  String status = getStatusReport();
  
  // 添加运行时信息
  status += "运行时间: " + String(millis() / 1000) + "秒\n";
  status += "可用内存: " + String(ESP.getFreeHeap() / 1024) + "KB\n";
  status += "CPU频率: " + String(getCpuFrequencyMhz()) + "MHz\n";
  
  return status;
}

String DeviceStateManager::getStatusJson(bool includeHistory) {
  DynamicJsonDocument doc(DeviceStateConfig::JSON_DOCUMENT_SIZE);
  
  // 基本状态信息
  doc["system_state"] = stateToString(getSystemState());
  doc["device_state"] = deviceStateToString(getDeviceState());
  doc["network_state"] = networkStateToString(getNetworkState());
  doc["timestamp"] = millis();
  
  // 绘图会话信息
  DrawingSession session = getDrawingSession();
  JsonObject drawingObj = doc.createNestedObject("drawing_session");
  drawingObj["active"] = session.isActive;
  drawingObj["paused"] = session.isPaused;
  drawingObj["stream_mode"] = session.isStreamMode;
  drawingObj["pattern_name"] = session.getPatternName();
  drawingObj["current_index"] = session.currentIndex;
  drawingObj["total_points"] = session.totalPoints;
  drawingObj["progress_percent"] = session.progressPercent;
  drawingObj["estimated_time_left"] = session.estimatedTimeLeft;
  drawingObj["start_time"] = session.startTime;
  
  // 系统信息
  JsonObject systemObj = doc.createNestedObject("system_info");
  systemObj["uptime"] = millis() / 1000;
  systemObj["free_heap"] = ESP.getFreeHeap();
  systemObj["cpu_freq"] = getCpuFrequencyMhz();
  
  // 包含状态历史（可选）
  if (includeHistory) {
    JsonArray historyArray = doc.createNestedArray("state_history");
    if (takeMutexWithRetry(historyMutex, 100)) { // 短超时避免阻塞
      for (uint8_t i = 0; i < historyCount; i++) {
        uint8_t index = (historyIndex - historyCount + i + DeviceStateConfig::MAX_STATE_HISTORY) % DeviceStateConfig::MAX_STATE_HISTORY;
        StateTransition& transition = stateHistory[index];
        
        JsonObject transitionObj = historyArray.createNestedObject();
        transitionObj["from_state"] = stateToString(transition.fromState);
        transitionObj["to_state"] = stateToString(transition.toState);
        transitionObj["timestamp"] = transition.timestamp;
        transitionObj["reason"] = transition.reason;
      }
      xSemaphoreGive(historyMutex);
    }
  }
  
  String result;
  serializeJson(doc, result);
  return result;
}

String DeviceStateManager::getDrawingSessionJson() {
  DynamicJsonDocument doc(512);
  
  DrawingSession session = getDrawingSession();
  doc["active"] = session.isActive;
  doc["paused"] = session.isPaused;
  doc["stream_mode"] = session.isStreamMode;
  doc["pattern_name"] = session.getPatternName();
  doc["current_index"] = session.currentIndex;
  doc["total_points"] = session.totalPoints;
  doc["progress_percent"] = session.progressPercent;
  doc["estimated_time_left"] = session.estimatedTimeLeft;
  doc["start_time"] = session.startTime;
  doc["last_update_time"] = session.lastUpdateTime;
  
  String result;
  serializeJson(doc, result);
  return result;
}

// ==================== 状态历史管理方法 ====================

void DeviceStateManager::clearStateHistory() {
  if (takeMutexWithRetry(historyMutex)) {
    historyIndex = 0;
    historyCount = 0;
    memset(stateHistory, 0, sizeof(stateHistory));
    xSemaphoreGive(historyMutex);
    
    Serial.println("🗑️ 状态历史已清空");
  }
}

String DeviceStateManager::getStateHistoryJson() {
  DynamicJsonDocument doc(DeviceStateConfig::JSON_DOCUMENT_SIZE);
  JsonArray historyArray = doc.createNestedArray("history");
  
  if (takeMutexWithRetry(historyMutex)) {
    for (uint8_t i = 0; i < historyCount; i++) {
      uint8_t index = (historyIndex - historyCount + i + DeviceStateConfig::MAX_STATE_HISTORY) % DeviceStateConfig::MAX_STATE_HISTORY;
      StateTransition& transition = stateHistory[index];
      
      JsonObject transitionObj = historyArray.createNestedObject();
      transitionObj["from_state"] = stateToString(transition.fromState);
      transitionObj["to_state"] = stateToString(transition.toState);
      transitionObj["timestamp"] = transition.timestamp;
      transitionObj["reason"] = transition.reason;
    }
    xSemaphoreGive(historyMutex);
  }
  
  doc["count"] = historyCount;
  doc["max_entries"] = DeviceStateConfig::MAX_STATE_HISTORY;
  
  String result;
  serializeJson(doc, result);
  return result;
}

StateTransition DeviceStateManager::getLastStateTransition() {
  StateTransition transition = {};
  
  if (takeMutexWithRetry(historyMutex)) {
    if (historyCount > 0) {
      uint8_t lastIndex = (historyIndex - 1 + DeviceStateConfig::MAX_STATE_HISTORY) % DeviceStateConfig::MAX_STATE_HISTORY;
      transition = stateHistory[lastIndex];
    }
    xSemaphoreGive(historyMutex);
  }
  
  return transition;
}

// ==================== 回调设置方法 ====================

void DeviceStateManager::setStateChangeCallback(void (*callback)(SystemState, SystemState)) {
  stateChangeCallback = callback;
}

void DeviceStateManager::setNetworkStateCallback(void (*callback)(NetworkState, NetworkState)) {
  networkStateCallback = callback;
}

void DeviceStateManager::setDrawingProgressCallback(void (*callback)(uint32_t, uint32_t)) {
  drawingProgressCallback = callback;
}

// ==================== 状态验证方法 ====================

bool DeviceStateManager::canStartDrawing() {
  SystemState sysState = getSystemState();
  DeviceRunState devState = getDeviceState();
  return (sysState == STATE_IDLE) && (devState == DEVICE_ACTIVE);
}

bool DeviceStateManager::canStartHoming() {
  SystemState sysState = getSystemState();
  DeviceRunState devState = getDeviceState();
  return (sysState == STATE_IDLE) && (devState == DEVICE_ACTIVE);
}

bool DeviceStateManager::canExecuteMotorCommand() {
  DeviceRunState devState = getDeviceState();
  return devState == DEVICE_ACTIVE;
}

bool DeviceStateManager::canEnterSleepMode() {
  SystemState sysState = getSystemState();
  DrawingSession session = getDrawingSession();
  return (sysState == STATE_IDLE) && !session.isActive;
}

bool DeviceStateManager::canConnectNetwork() {
  SystemState sysState = getSystemState();
  return sysState != STATE_EMERGENCY;
}

// ==================== 批量操作方法 ====================

void DeviceStateManager::getAllStates(SystemState& sysState, DeviceRunState& devState, NetworkState& netState) {
  if (takeMutexWithRetry(stateMutex)) {
    sysState = systemState;
    devState = deviceState;
    netState = networkState;
    xSemaphoreGive(stateMutex);
  }
}

bool DeviceStateManager::setAllStates(SystemState sysState, DeviceRunState devState, NetworkState netState) {
  bool success = true;
  
  success &= setSystemState(sysState, "批量状态更新");
  success &= setDeviceState(devState, "批量状态更新");
  success &= setNetworkState(netState, "批量状态更新");
  
  if (success) {
    Serial.println("✅ 批量状态更新成功");
  } else {
    Serial.println("❌ 批量状态更新部分失败");
  }
  
  return success;
}
